package com.kaiwukj.android.ufamily.mvp.ui.page.dynamic.person;

import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.appcompat.widget.Toolbar;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.fragment.app.Fragment;
import androidx.viewpager2.adapter.FragmentStateAdapter;
import androidx.viewpager2.widget.ViewPager2;

import com.afollestad.materialdialogs.MaterialDialog;
import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.blankj.utilcode.util.BarUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.StringUtils;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.google.android.material.appbar.AppBarLayout;
import com.google.android.material.tabs.TabLayout;
import com.google.android.material.tabs.TabLayoutMediator;
import com.kaiwukj.android.mcas.di.component.AppComponent;
import com.kaiwukj.android.ufamily.R;
import com.kaiwukj.android.ufamily.app.base.review.BaseMvpActivity;
import com.kaiwukj.android.ufamily.app.constant.ARouterUrlKt;
import com.kaiwukj.android.ufamily.di.component.DaggerDynamicComponent;
import com.kaiwukj.android.ufamily.di.module.DynamicModule;
import com.kaiwukj.android.ufamily.mvp.helper.GlideEngine;
import com.kaiwukj.android.ufamily.mvp.http.entity.event.DynamicAttentionEvent;
import com.kaiwukj.android.ufamily.mvp.http.entity.event.HomeEvent;
import com.kaiwukj.android.ufamily.mvp.http.entity.event.UpdateUserInfoEvent;
import com.kaiwukj.android.ufamily.mvp.http.entity.result.DynamicResult;
import com.kaiwukj.android.ufamily.mvp.http.entity.result.UserResult;
import com.kaiwukj.android.ufamily.mvp.ui.page.dynamic.DynamicContract;
import com.kaiwukj.android.ufamily.mvp.ui.page.home.message.ChatActivity;
import com.kaiwukj.android.ufamily.utils.DialogUtilsKt;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.listener.OnResultCallbackListener;
import com.qmuiteam.qmui.util.QMUIStatusBarHelper;
import com.qmuiteam.qmui.widget.roundwidget.QMUIRoundButton;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

@Route(path = ARouterUrlKt.DynamicPersonUrl)
public class PersonDynamicActivity extends BaseMvpActivity<PersonDynamicPresenter> implements DynamicContract.PersonIndexView {

    @BindView(R.id.refresh_layout)
    SmartRefreshLayout refreshLayout;
    @BindView(R.id.iv_bar_bg)
    ImageView ivBarBg;
    @BindView(R.id.tab)
    TabLayout tabLayout;
    @BindView(R.id.vp_content)
    ViewPager2 vpContent;

    @BindView(R.id.app_bar_layout)
    AppBarLayout appBarLayout;
    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.iv_avatar_bar)
    ImageView ivAvatarBar;
    @BindView(R.id.tv_nickname_bar)
    TextView tvNicknameBar;
    @BindView(R.id.iv_avatar)
    ImageView ivAvatar;
    @BindView(R.id.tv_user_name)
    TextView tvUserName;
    @BindView(R.id.tv_user_desc)
    TextView tvUserDesc;
    @BindView(R.id.iv_sex)
    QMUIRoundButton tvSex;
    @BindView(R.id.tv_attention_num)
    TextView tvAttentionNum;
    @BindView(R.id.tv_fans_num)
    TextView tvFansNum;
    @BindView(R.id.tv_like_num)
    TextView tvLikeNum;
    @BindView(R.id.iv_edit)
    View ivEdit;

    @BindView(R.id.container_back)
    ViewGroup containerBack;
    @BindView(R.id.container_more)
    ViewGroup containerMore;
    @BindView(R.id.container_bottom)
    ViewGroup containerBottom;
    @BindView(R.id.btn_attention_bottom)
    Button btnAttention;

    private MaterialDialog reportDialog;

    private boolean isNeedRefresh = false;

    @Autowired
    int userId = -1;

    private PersonIndexChildFragment userFragment;
    private UserResult currentUser;

    @OnClick({R.id.container_back, R.id.container_back_bar})
    void onBackClick() {
        onBackPressedSupport();
    }

    @OnClick({R.id.container_fans, R.id.container_attention})
    void onFansClick(View view) {
        UserResult userResult = getApp().getUserInfo();
        if (userResult == null) return;
        if (view.getId() == R.id.container_attention) {
            ARouter.getInstance().build(ARouterUrlKt.PersonFansUrl)
                    .withInt("type", 0)
                    .withInt("userId", userId)
                    .navigation();
        } else {
            ARouter.getInstance().build(ARouterUrlKt.PersonFansUrl)
                    .withInt("type", 1)
                    .withInt("userId", userId)
                    .navigation();
        }
    }

    @OnClick(R.id.iv_edit)
    void intent2Edit() {
        ARouter.getInstance().build(ARouterUrlKt.PersonInfoUpdateUrl)
                .navigation();
    }

    @OnClick(R.id.btn_attention_bottom)
    void onAttentionClick() {
        if (currentUser.isConcern()) {
            showMessageOKCancel(this, "是否不再关注TA",
                    v -> mPresenter.cancelAttention(currentUser.getId()));
        } else {
            mPresenter.attention(currentUser.getId());
        }
    }

    @OnClick(R.id.container_more)
    void onMoreClick() {
        showReportDialog();
    }

    @OnClick(R.id.btn_chat_bottom)
    void onChatClick() {
        /*if (!EMClient.getInstance().isConnected()) {
            showMessage("未连接到聊天服务器");
        } else if (currentUser.getHxName().equals(EMClient.getInstance().getCurrentUser()))
            Toast.makeText(this, R.string.Cant_chat_with_yourself, Toast.LENGTH_SHORT).show();
        else {
            // start chat acitivity
            UserCacheManager.save(String.valueOf(currentUser.getId()), currentUser.getNickName(), currentUser.getHeadImg());
            Intent intent = new Intent(this, ChatActivity.class);
            // it's single chat
            intent.putExtra(EaseConstant.EXTRA_CHAT_TYPE, EaseConstant.CHATTYPE_SINGLE);
            intent.putExtra(EaseConstant.EXTRA_USER_ID, String.valueOf(currentUser.getHxName()));
            intent.putExtra(EaseConstant.EXTRA_USER_NAME, currentUser.getNickName());
            startActivity(intent);
        }*/
        ChatActivity.startSingleChat(this, currentUser);
    }

    @OnClick(R.id.iv_bar_bg)
    void onBgImgClick() {
        if (userId == getApp().getUserInfo().getId()) {
            changedBgImg();
        }
    }

    @OnClick(R.id.iv_avatar)
    void onAvatarClick() {
        LogUtils.d("----------avatar----------");
    }

    @Override
    public void setupActivityComponent(@NonNull AppComponent appComponent) {
        super.setupActivityComponent(appComponent);
        DaggerDynamicComponent.builder()
                .appComponent(appComponent)
                .dynamicModule(new DynamicModule(this))
                .build().inject(this);
    }

    @Override
    protected int getLayoutId() {
        ARouter.getInstance().inject(this);
        QMUIStatusBarHelper.translucent(this);
        QMUIStatusBarHelper.setStatusBarLightMode(this);
        return R.layout.activity_dynamic_person;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        UserResult userResult = getApp().getUserInfo();
        if (userResult == null) return;
        if (userId < 0) {
            userId = userResult.getId();
        }

        ConstraintLayout.LayoutParams layoutParams = (ConstraintLayout.LayoutParams) containerBack.getLayoutParams();
        layoutParams.topMargin = BarUtils.getStatusBarHeight();
        containerBack.setLayoutParams(layoutParams);

        ConstraintLayout.LayoutParams layoutParamsMore = (ConstraintLayout.LayoutParams) containerMore.getLayoutParams();
        layoutParamsMore.topMargin = BarUtils.getStatusBarHeight();
        containerMore.setLayoutParams(layoutParamsMore);

        appBarLayout.addOnOffsetChangedListener((appBarLayout, verticalOffset) -> {
            //appBarLayout.setExpanded();
            int minHeight = appBarLayout.getMinimumHeightForVisibleOverlappingContent();
            if (minHeight < Math.abs(verticalOffset) - BarUtils.getStatusBarHeight() - tabLayout.getHeight()) {
                toolbar.setVisibility(View.VISIBLE);
            } else {
                toolbar.setVisibility(View.GONE);
            }

        });

        List<Fragment> fragmentList = new ArrayList<>();
        PersonDynamicFragment fragment01 = PersonDynamicFragment.newInstance(userId);
        userFragment = PersonIndexChildFragment.newInstance();
        fragmentList.add(fragment01);
        fragmentList.add(userFragment);

        List<String> titles = new ArrayList<>();
        titles.add("动态");
        titles.add("资料");

        vpContent.setAdapter(new FragmentStateAdapter(this) {
            @NonNull
            @Override
            public Fragment createFragment(int position) {
                return fragmentList.get(position);
            }

            @Override
            public int getItemCount() {
                return fragmentList.size();
            }
        });

        new TabLayoutMediator(tabLayout, vpContent,
                (tab, position) -> tab.setText(titles.get(position))).attach();

        refreshLayout.setEnableLoadMore(false);

        refreshLayout.setOnRefreshListener(refreshLayout -> {
            mPresenter.fetchInfo(userId);
            fragment01.setRefresh();
        });


    }

    @Override
    protected void initData(Bundle savedInstanceState) {
        if (getApp().getUserInfo() != null) {
            if (getApp().getUserInfo().getId() == userId) {
                containerBottom.setVisibility(View.GONE);
                ivEdit.setVisibility(View.VISIBLE);
                containerMore.setVisibility(View.GONE);
            }
        }
        mPresenter.fetchInfo(userId);
    }


    @Override
    protected void onResume() {
        super.onResume();
        if (isNeedRefresh) {
            isNeedRefresh = false;
            mPresenter.fetchInfo(userId);
        }
    }


    @Subscribe
    public void onUserInfoUpdateEvent(UpdateUserInfoEvent event) {
        if (event.getCode() == UpdateUserInfoEvent.RESP_OK) {
            isNeedRefresh = true;
        }
    }

    @Subscribe
    public void onAttentionEvent(DynamicAttentionEvent event) {
        if (userId == getApp().getUserInfo().getId()) {
            tvAttentionNum.setText(String.valueOf(getApp().getUserInfo().getConcernNum()));
        }
    }

    @Override
    public void onGetPersonDynamic(List<DynamicResult> circleHomeResults) {

    }

    @Override
    public void onGetPersonInfo(UserResult result) {

        currentUser = result;
        refreshLayout.finishRefresh(500);

        if (userFragment != null) {
            userFragment.setData(result);
        }

        String bgImg = "https://c-ssl.duitang.com/uploads/item/202004/22/20200422225808_ceqvp.jpg";
        if (!StringUtils.isEmpty(result.getBackImg())) {
            bgImg = result.getBackImg();
        }
        Glide.with(this)
                .load(bgImg)
                .diskCacheStrategy(DiskCacheStrategy.ALL)
                .into(ivBarBg);

        Glide.with(this)
                .load(result.getHeadImg())
                .placeholder(R.mipmap.icon_common_head_place_holder)
                .diskCacheStrategy(DiskCacheStrategy.ALL)
                .into(ivAvatar);

        Glide.with(this)
                .load(result.getHeadImg())
                .diskCacheStrategy(DiskCacheStrategy.ALL)
                .into(ivAvatarBar);
        tvUserName.setText(result.getNickName());
        tvNicknameBar.setText(result.getNickName());
        tvUserDesc.setText(result.getSignature());
        tvSex.setText(result.getGenderStr());
        tvAttentionNum.setText(String.valueOf(result.getConcernNum()));
        tvFansNum.setText(String.valueOf(result.getFansNum()));
        tvLikeNum.setText(String.valueOf(result.getPraiseNum()));
        btnAttention.setText(currentUser.isConcern() ? "已关注" : "关注");
    }

    @Override
    public void onTaskSuccess(int taskId) {
        super.onTaskSuccess(taskId);
        if (taskId == PersonDynamicPresenter.USER_BG_UPDATE) {
            hideLoading();
            UserResult result = getApp().getUserInfo();
            String bgImg = "https://c-ssl.duitang.com/uploads/item/202004/22/20200422225808_ceqvp.jpg";
            if (!StringUtils.isEmpty(result.getBackImg())) {
                bgImg = result.getBackImg();
            }
            Glide.with(this)
                    .load(bgImg)
                    .diskCacheStrategy(DiskCacheStrategy.ALL)
                    .into(ivBarBg);
        } else if (taskId == PersonDynamicPresenter.ATTENTION) {
            showMessage("关注成功");
            currentUser.setConcernStatus(1);
            btnAttention.setText("已关注");
            EventBus.getDefault().post(new HomeEvent(HomeEvent.POST_ATTENTION, currentUser.getId(), 0));
        } else if (taskId == PersonDynamicPresenter.ATTENTION_CANCEL) {
            showMessage("取消成功");
            currentUser.setConcernStatus(0);
            btnAttention.setText("关注");
            EventBus.getDefault().post(new HomeEvent(HomeEvent.POST_ATTENTION_CANCEL, currentUser.getId(), 0));
        } else if (taskId == PersonDynamicPresenter.BLOCK_USER) {
            onBackPressedSupport();
        }
    }

    @Override
    public void onTaskErr(int taskId) {
        super.onTaskErr(taskId);
        hideLoading();
    }

    private void changedBgImg() {
        PictureSelector.create(this)
                .openGallery(PictureMimeType.ofImage())
                .imageEngine(GlideEngine.createGlideEngine())
                .isCompress(true)
                .maxSelectNum(1)
                .withAspectRatio(1, 1)
                //.enableCrop(true)
                .theme(R.style.MyImagePickerStyle)
                .forResult(new OnResultCallbackListener<LocalMedia>() {
                    @Override
                    public void onResult(List<LocalMedia> result) {
                        showLoading("正在处理...");
                        mPresenter.uploadFile(result.get(0).getCompressPath());
                    }

                    @Override
                    public void onCancel() {

                    }
                });
    }

    private void showReportDialog() {
        if (reportDialog == null) {
            reportDialog = DialogUtilsKt.showBottomReportDialog(this, v -> {
                switch (v.getId()) {
                    case R.id.tv_block_this_user:
                        mPresenter.blockUser(currentUser.getId());
                        reportDialog.cancel();
                        break;
                }
            });
        }
        reportDialog.show();
    }
}
